package com.second.app.superthread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author GYZ
 * @Date 2024/1/23
 * <pre>
 *  isBroken:
 *     查询此屏障是否处于损坏状态
 *     从运行结果看：有一个线程出现异常报错，则其他线程继续等待，并不影响程序运行的主流程
 *
 *     如果 if(Thread.currentThread().getName().equalsIgnoreCase("Thread-2")){
 *                 System.out.println("Thread-2 进来了");
 *                 Thread.sleep(5000);
 *                 Integer.parseInt("a")};
 *              将上面这段代码，做出改动，如下
 *      if(Thread.currentThread().getName().equalsIgnoreCase("Thread-2")){
 *                 System.out.println("Thread-2 进来了");
 *                 Thread.sleep(5000);
 *       Thread.currentThread().interrupt();
 *      }
 *     从运行结果来看，全部线程进入了catch语句块，其中线程Thread-2进入了Interrupted的exception语句块
 *     其他三个进入BrokenBarrierException异常。
 *     所以如果有一个线程由于中断或者超时提前离开屏障点，其他所等待的线程也会抛出BrokenBarrierException或者Interrupted异常
 *     并且离开屏障点.
 *
 * </pre>
 */
public class CyclicBarrierIsBroken {
    public static void main(String[] args) {

        int parties = 4;
        CyclicBarrier cbRef = new CyclicBarrier(parties, () -> System.out.println("都到了！"));

        BrokenService brokenService = new BrokenService(cbRef);

        BrokenThread[] brokenThreads = new BrokenThread[4];

        for (int i=0;i<brokenThreads.length;i++){
            brokenThreads[i] = new BrokenThread(brokenService);
            brokenThreads[i].start();
        }
    }
}

class BrokenService{

    private final CyclicBarrier cyclicBarrier;

    public BrokenService(CyclicBarrier cyclicBarrier){
        this.cyclicBarrier =cyclicBarrier;
    }

    private void beginRun(int count){
        try {
            System.out.println(Thread.currentThread().getName()+" 到了 在等待其他人开始起跑 ");
            if(Thread.currentThread().getName().equalsIgnoreCase("Thread-2")){
                System.out.println("Thread-2 进来了");
                Thread.sleep(5000);
                //Integer.parseInt("a");
                Thread.currentThread().interrupt();
            }
            cyclicBarrier.await();
            System.out.println(" 都到了，开始跑！");
            System.out.println(Thread.currentThread().getName()+" 到达终点，并结束第"+count+"赛段");
        } catch (InterruptedException e) {
            System.out.println("进入InterruptedException e "+cyclicBarrier.isBroken());
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            System.out.println("进入BrokenBarrierException e "+cyclicBarrier.isBroken());
            e.printStackTrace();
        }
    }

    public void testA(){
        for (int i=0;i<1;i++){
            beginRun(i+1);
        }
    }
}

class BrokenThread extends Thread{
    private final BrokenService brokenService;

    public BrokenThread(BrokenService brokenService){
       this.brokenService =brokenService;
    }

    @Override
    public void run() {
        brokenService.testA();
    }
}
